package cc.md888.app.application.account;

import cc.md888.app.exception.BizRuntimeException;
import cc.md888.app.model.account.AccountAuthVO;
import cc.md888.app.utils.AESUtil;
import cc.md888.result.ResultCode;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Map;

@Component
public class FacebookAccountService {

    @Value("${robot.account.aes-key:}")
    private String aesKey;
    @Value("${robot.account.auth-file.path:}")
    private String authFileDir;

    /**
     * 获取账号认证文件信息
     * @return
     */
    public AccountAuthVO getAccountAuthInfo(String authToken){
        String uid = AESUtil.decrypt(authToken, aesKey);
        if (StringUtils.isEmpty(uid)) {
            throw BizRuntimeException.from(ResultCode.ERROR, "认证文件令牌错误");
        }
        String filename = uid + ".tar.gz";
        File authFile = new File(authFileDir, filename);
        if(!authFile.exists()){
            throw BizRuntimeException.from(ResultCode.ERROR, "认证文件不存在");
        }

        try {
            FileInputStream fis = new FileInputStream(authFile);
            byte[] contentBytes = IOUtils.toByteArray(fis);
            String content = Base64.getMimeEncoder().encodeToString(contentBytes);

            AccountAuthVO accountAuthVO = new AccountAuthVO();
            accountAuthVO.setUid(uid);
            accountAuthVO.setContent(content);
            return accountAuthVO;
        } catch (IOException e) {
            throw BizRuntimeException.from(ResultCode.ERROR, "读取认证文件失败");
        }
    }



    public static void main(String[] args) {
        String uuid = AESUtil.encrypt("61583030300219", "707b7831ed9aefe0bd72fa5cc5a25d8c");
        System.out.println(uuid);
    }
}
